package com.example.new_trace_pda_check;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.example.new_trace_pda_check.databinding.ActivityMainBinding;
import com.google.gson.Gson;
import com.huawei.hms.hmsscankit.ScanUtil;
import com.huawei.hms.ml.scan.HmsScan;
import com.huawei.hms.ml.scan.HmsScanAnalyzerOptions;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    private ActivityMainBinding mBinding;
   /* private String urlBox = "http://192.168.1.118:1098" + "/api/adminScanInquireSourceBox";*/
//    private String urlBox = "http://192.168.1.109:1125" + "/api/adminScanInquireSourceBox";
//    private String urlContainer = "http://192.168.1.109:1125" + "/api/adminScanInquireSourceContainer";
//
//    private String urlkk = "http://192.168.1.109:1125" + "/api/unbundle";


//    private String urlBox = "http://120.77.146.146:1125" + "/api/adminScanInquireSourceBox";
//    private String urlContainer = "http://120.77.146.146:1125" + "/api/adminScanInquireSourceContainer";
//
//    private String urlkk = "http://120.77.146.146:1125" + "/api/unbundle";

    private String urlBox = "http://47.100.110.3:1125" + "/api/adminScanInquireSourceBox";
    private String urlContainer = "http://47.100.110.3:1125" + "/api/adminScanInquireSourceContainer";

    private String urlkk = "http://47.100.110.3:1125" + "/api/unbundle";

    private MyReceiver broadcastReceiver;
    private String mCode;
    private Handler handler;
    private Runnable runnable = () -> {
        String code = mCode;
        Log.d("数据", code);
        if (TextUtils.isEmpty(code)) return;
        if (code.length() == 17) {
            postBoxNum(code);
        } else if (code.length() == 16) {
            postContainerNumber(code);
        } else {
            showToast("error:请扫码箱码/盒码");
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        PermissionUtil.isGrantExternalRW(this, 1);

        mBinding = ActivityMainBinding.inflate(getLayoutInflater());

        setContentView(mBinding.getRoot());
        init();
    }

    private void init() {
//        mBinding.btnUnbind.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                String code = mCode;
//                postSao(code);
//            }
//        });
        setTitle("扫码查询");
        handler = new Handler(getMainLooper());
        initBroadcastReceiver();
    }

    private void setInit() {
        runOnUiThread(() -> {
            mBinding.tvContainer.setText("");
            mBinding.tvCode.setText("");
            mBinding.tvBox.setText("");
            mBinding.tvName.setText("");
        });
    }

    private void initBroadcastReceiver() {
        if (broadcastReceiver == null) {
            IntentFilter filter = new IntentFilter();
            filter.addAction("android.intent.action.result");
            broadcastReceiver = new MyReceiver(string -> {
                mCode = string;
                Log.d("数据00", mCode);
                if (!TextUtils.isEmpty(mCode)) {
                    handler.post(runnable);
                }
            });
            registerReceiver(broadcastReceiver, filter);
        }
    }

    private void postBoxNum(String code) {
        mBinding.tvType.setText("箱码:" + code);
        Map<String, String> map = new HashMap<>();
        map.put("boxNumber", code);
        showDialog("正在查询箱码");
        setInit();
        OkhttpUtil.getInstance().post(urlBox, map, new OkhttpUtil.requestMessage() {
            @Override
            public void requestFail() {
                canDialog();
            }

            @Override
            public void requestSuccess(Response response) throws IOException {
                canDialog();
                String responseData = response.body().string();
                Log.d("数据", responseData);
                BoxBean bean = new Gson().fromJson(responseData, BoxBean.class);
                if (TextUtils.isEmpty(bean.getStatus()) || bean.getStatus().equals("0")) {
                    showToast(bean.getError());
                    return;
                }
                runOnUiThread(() -> {

                    mBinding.tvContainer.setText(bean.getDataBind().getContainerNumber());
                    mBinding.tvCode.setText(bean.getDataBind().getArticleid());
                    String boxs = bean.getDataBind().getBoxNumbers().substring(0, bean.getDataBind().getBoxNumbers().length() - 1).replace(",", "\n");
                    mBinding.tvBox.setText(boxs);
                    mBinding.tvName.setText(bean.getDataBind().getInStockNumber());
                });
            }
        });
    }

    private void postContainerNumber(String code) {
        mBinding.tvType.setText("盒码:" + code);
        Map<String, String> map = new HashMap<>();
        map.put("containerNumber", code);
        showDialog("正在查询盒码");
        setInit();
        OkhttpUtil.getInstance().post(urlContainer, map, new OkhttpUtil.requestMessage() {
            @Override
            public void requestFail() {
                canDialog();
            }

            @Override
            public void requestSuccess(Response response) throws IOException {
                canDialog();
                String responseData = response.body().string();
                Log.d("数据", responseData);
                BoxBean bean = new Gson().fromJson(responseData, BoxBean.class);
                if (TextUtils.isEmpty(bean.getStatus()) || bean.getStatus().equals("0")) {
                    showToast(bean.getError());
                    return;
                }
                runOnUiThread(() -> {

                    mBinding.tvContainer.setText(bean.getDataBind().getContainerNumber());
                    mBinding.tvCode.setText(bean.getDataBind().getArticleid());
                    String boxs = bean.getDataBind().getBoxNumbers().substring(0, bean.getDataBind().getBoxNumbers().length() - 1).replace(",", "\n");
                    mBinding.tvBox.setText(boxs);
                    mBinding.tvName.setText(bean.getDataBind().getInStockNumber());
                });
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(Menu.NONE, 1, 0, "[  -  ]").setShowAsAction(1);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == 1) {
            ScanUtil.startScan(this, 0x01, new HmsScanAnalyzerOptions.Creator().create());
        }
        return true;
    }

    //返回值
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK || data == null) {
            return;
        }
        if (requestCode == 0x01) {
            HmsScan obj = data.getParcelableExtra(ScanUtil.RESULT);
            if (obj != null) {
                mCode = obj.originalValue;
                if (TextUtils.isEmpty(mCode)) return;
                handler.post(runnable);
            }
        }
    }


    public void showToast(String msg) {
        runOnUiThread(() -> Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show());
    }

    //加载进度弹窗
    private ProgressDialog progressDialog;

    public void showDialog(String title) {
        runOnUiThread(() -> {
            if (progressDialog == null) {
                progressDialog = new ProgressDialog(this);
            }
            if (progressDialog.isShowing()) {
                return;
            }
            progressDialog.setTitle(title);
            progressDialog.setMessage("Loading...");
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.show();
        });
    }

    //关闭进度圈圈
    protected void canDialog() {
        if (progressDialog != null) {
            runOnUiThread(() -> progressDialog.cancel());
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
        if (broadcastReceiver != null) {
            Log.d("数据", "关闭广播 ");
            unregisterReceiver(broadcastReceiver);
        }
    }

    private void postSao(String code) {

        Map<String, String> map = new HashMap<>();
        map.put("containerNumber", code);
        setInit();
        OkhttpUtil.getInstance().post(urlkk, map, new OkhttpUtil.requestMessage() {
            @Override
            public void requestFail() {
                canDialog();
            }

            @Override
            public void requestSuccess(Response response) throws IOException {
                canDialog();
                String responseData = response.body().string();
                Log.d("数据", responseData);
                BoxBean bean = new Gson().fromJson(responseData, BoxBean.class);

                    if (TextUtils.isEmpty(bean.getStatus()) || bean.getStatus().equals("0")) {

                        Log.d("aaaaaaaaaaaaaaaaaaaaaa", "requestSuccess: " + bean.getError());
                        Toast.makeText(MainActivity.this, bean.getError(), Toast.LENGTH_SHORT).show();



                        return;
                    }else{
                        runOnUiThread(() -> {
                            mBinding.tvType.setText("");
                            mBinding.tvContainer.setText("");
                            mBinding.tvCode.setText("");
                            //String boxs = bean.getDataBind().getBoxNumbers().substring(0, bean.getDataBind().getBoxNumbers().length() - 1).replace(",", "\n");
                            mBinding.tvBox.setText("");
                            mBinding.tvName.setText("");
                            showToast("解绑成功！");
                        });
                    }

            }
        });
    }


}
